package service.impl;

import dao.UserDao;
import dao.impl.UserDaoImpl;
import pojo.User;
import service.UserService;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashSet;

public class UserServiceImpl implements UserService {
    private UserDao userDao = new UserDaoImpl();
    private boolean flag = false;

    public boolean checkUserLogin(User user1) throws SQLException, ClassNotFoundException {
        User user = new User();
        boolean exit = false;
        UserService userService = new UserServiceImpl();
        User userLogin = userService.findUserByUsername(user1.getUsename());
        if (userLogin == null) {
            exit = true;
        }
        boolean checkUsename = user.setUsename(user1.getUsename());
        boolean checkPassword = user.setPassword(user1.getPassword());
        user.setGender(user1.getGender());
        boolean checkTelephone = user.setTelephone(user1.getTelephone());
        boolean checkAge = user.setAge(user1.getAge());
        boolean check = false;
        if (exit && checkUsename && checkPassword && checkTelephone && checkAge) check = true;
        return check;
    }

    @Override
    public boolean userLogin(String usename, String password) throws SQLException {
        flag = userDao.login(usename, password);
        return flag;
    }

    @Override
    public boolean userRegist(User user) throws SQLException {
        flag = userDao.addRegist(user);
        return flag;
    }


    public User findUser(Integer uid) throws SQLException, ClassNotFoundException {
        User user = new User();
        user = userDao.getUser(uid);
        return user;
    }

    public User findUserByUsername(String usename) throws SQLException, ClassNotFoundException {
        User user = new User();
        user = userDao.findUserInformation(usename);
        return user;
    }


    public boolean updateUserInformation(User user) throws SQLException, IllegalAccessException {
        flag = userDao.update(user);
        return flag;
    }

    public ArrayList<User> areaUserList(String type) throws SQLException, ClassNotFoundException {
        ArrayList<User> areaUserList = new ArrayList<>();
        HashSet<String> userUsename = userDao.areaUserUsename(type);
        ArrayList<User> allUsers = userDao.allUsers();
        for (String s : userUsename) {
            for (Integer i = 0; i < allUsers.size(); i++) {
                if (allUsers.get(i).getUsename().equals(s)) {
                    areaUserList.add(allUsers.get(i));
                }
            }
        }
        return areaUserList;
    }
}
